import os
import sys, time

BARE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BARE_DIR)
from ATM.core import auth
from ATM.core import log
from ATM.core import transaction
from ATM.core import account
from ATM.conf import settings

# logger()函数执行，并且返回了logger，可以进行调用warn方法进行日志写入
trans_logger = log.log('transaction')
access_logger = log.log('access')

user_data = {
    'account_id': None,
    'is_authenticated': False,
    'account_data': None
}


def account_info(acc_data):
    print(user_data['account_data'])


def repay(acc_data):
    account_data = user_data['account_data']
    # for k,v in account_data.items():
    #     print(k,v)
    current_balance = """
    ----------- BALANCE INFO --------
            Credit:%s
            Balance:%s
    """ % (account_data['credit'], account_data['balance'])
    print(current_balance)
    back_flag = False  # 设置标志，输入b跳出while循环
    while not back_flag:
        repay_amount = input("\033[33;1mInput repay amount:\033[0m").strip()
        if len(repay_amount) > 0 and repay_amount.isdigit():
            # print('ddd 00')
            new_balance = transaction.make_transaction(trans_logger, account_data, 'repay', repay_amount)
            # print(new_balance)
            if new_balance:
                print("""\033[42;1mNew Balance:%s\033[0m""" % (new_balance['balance']))
        else:
            print('\033[31;1m[%s] is not a valid amount,only accept integer!\033[0m' % repay_amount)
        if repay_amount == 'b':
            back_flag = True


def withdraw(acc_data):
    """
    取款
    :param acc_data: 变成了数据库数据,而且是字典的格式
    :return:
    """
    accout_data = account.load_account(acc_data['account_id'])  # 再去数据库拿一遍数据，有点多余
    current_balance = '''
    ------- BALANCE INFO -------
          Credit:   %s
          Balance:  %s
    ''' % (accout_data['credit'], accout_data['balance'])
    print(current_balance)
    back_flag = False
    while not back_flag:
        withdraw_amount = input("\033[33;1mInput withdraw amount:\033[0m").strip()
        if len(withdraw_amount) > 0 and withdraw_amount.isdigit():
            new_balance = transaction.make_transaction(trans_logger, accout_data, 'withdraw', withdraw_amount)
            if new_balance:
                print('''\033[42;1mNew Balance:%s\033[0m''' % (new_balance['balance']))
        else:
            print('\033[31;1m[%s] is not a valid amount,only accept integer!')
        if withdraw_amount == 'b':
            back_flag = True


def transfer(acc_data):
    """

    :param acc_data: 变成了数据库数据,而且是字典的格式
    :return:
    """
    account_data = account.load_account(acc_data['account_id'])
    current_balance = '''
        ------- BALANCE INFO -------
              Credit:   %s
              Balance:  %s''' % (account_data['credit'], account_data['balance'])
    print(current_balance)

    # 钱数必须是数字
    back_flag = False
    while not back_flag:
        tranfer_amount = input("\033[33;1mInput tranfer amount:\033[0m").strip()
        # 只支持整数
        if len(tranfer_amount) > 0 and tranfer_amount.isdigit():

            # 调用transaction，传入账号信息，交易类型，交易金额，交易日志
            new_account_data = transaction.make_transaction(trans_logger, account_data, 'transfer', tranfer_amount)
            if new_account_data:
                print("\033[42;1mNew Balance:%s\033[0m" % new_account_data['balance'])
        else:
            print('\033[31;1m[%s] is not a valid amount,only accept integer!')
        if tranfer_amount == 'b':
            back_flag = True


def pay_check(acc_data):  # 账单功能
    back_flag = False
    while not back_flag:
        Time_input = input("\033[33;1mplease input time(Y-M-D),输入b退出:\033[0m").strip()
        if Time_input == 'b':
            back_flag = True
            continue
        else:
            try:
                select_time = time.mktime(time.strptime(Time_input,'%Y-%m-%d'))  # print(select_time)
            except Exception as ValueError:
                print("清输入正确的日期格式")
                continue        # log_file = "atm_test/log/transactions.log"        log_file = "%s/log/%s" % (settings.BASE_DIR, settings.LOG_TYPES["transaction"])        # print(log_file)        with open(log_file,"r",encoding="utf-8") as f:            for i in f:   # for i in f : 是和大文件读写，不用写f,readlines()                i_times = i[0:10]                account_id = i[55:59]                #字符串相同还判断不出来，必须转换成数字才行,估计数字类型的得这样做                account_id = int(account_id)                user_data['account_data']['id'] = int(user_data['account_data']['id'])                # print("account_id:%s" %account_id)                i_time = time.mktime(time.strptime(i_times,'%Y-%m-%d'))                # print(i_time)                if i_time >= select_time and account_id == user_data['account_data']['id']:                    print(i)def logout(acc_data):    """    退出登录    :param acc_data:    :return:    """    q = input("\033[33;1mIf you want to quit,please input q:\033[0m").strip()    if q == 'q':        exit()    else:        print("请输入q")def interactive(acc_data):    """    :param acc_data:    :return:    """    # 加u是为了防止中文乱码    menu = u"""      --------- Oldboy Bank ---------    \033[32;1m1.账号信息    2.还款    3.取款    4.转账    5.账单    6.退出        \033[0m"""#这里比较牛的是写个字典，所以数字对应的是函数的内存地址    menu_dic = {        '1':account_info,        '2':repay,        '3':withdraw,        '4':transfer,        '5':pay_check,        '6':logout    }    exit_flag = False  #这个标记为有很重要，是循环的前提    while not exit_flag:        print(menu)        user_option = input(">>:").strip()        if user_option in menu_dic:   # for i in menu_dic 显示出的是字典的key            menu_dic[user_option](acc_data)def run():    """    认证字段为真，用户数据为数据库的数据，信息补全了    :return:    """    #经过执行acc_login之后，如果认证成功会改变user_data中的数据，认证成功字段置为真，赋予相应账号,    acc_data = auth.acc_login(user_data,access_logger) #acc_data变成了数据库数据,而且是字典的格式    if user_data['is_authenticated']:        user_data['account_data'] = acc_data        interactive(user_data)    else:        print("\033[31;1mOption does not exist!\033[0m")# run()
